package com.sgb.kjwl.view.ui.activity.business;

import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.PopupWindow;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityAddMemberBinding;
import com.sgb.kjwl.di.business.BusinessModule;
import com.sgb.kjwl.di.business.DaggerBusinessComponent;
import com.sgb.kjwl.model.entity.business.ApprovalFlowEntity;

import com.sgb.kjwl.model.entity.business.CompanyEntity;
import com.sgb.kjwl.model.entity.business.CreateMemberEntity;
import com.sgb.kjwl.model.entity.user.UnitEntity;
import com.sgb.kjwl.view.ui.adapter.business.ApprovalDepartAdapter;
import com.sgb.kjwl.view.ui.adapter.business.CompanyPopupwindowAdapter;
import com.sgb.kjwl.viewmodel.business.AddMemberModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.util.MToast;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

public class AddMemberActivity extends AppActivity {
    private ActivityAddMemberBinding binding;
    @Inject
    AddMemberModel viewModel;
    //企业服务类型
    private List<UnitEntity> comTypes = new ArrayList<>();
    private int comTypePosition;
    //会员等级
    private List<UnitEntity> memLevels = new ArrayList<>();
    private int memLevelPosition;

    //pop
    private GridLayoutManager leftManager;
    private boolean showPopup = false;
    private boolean popupCan = true;
    private PopupWindow window;
    private CompanyPopupwindowAdapter popupwindowAdapter;
    private List<com.sgb.kjwl.model.entity.business.CompanyEntity> companyEntities = new ArrayList<>();

    private CreateMemberEntity createMemberEntity = new CreateMemberEntity();

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerBusinessComponent.builder().appComponent(appComponent).businessModule(new BusinessModule(this)).build().inject(this);
    }

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, AddMemberActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected boolean statusBarDark() {
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(AddMemberActivity.this, R.layout.activity_add_member);
        binding.setViewModel(viewModel);

        viewModel.getFlow();
    }

    @Override
    protected void init() {
        binding.include.titleView.setText("新增会员");
        binding.include.ivBack.setOnClickListener(this);
        binding.llComType.setOnClickListener(this);
        binding.llMemLevel.setOnClickListener(this);
        binding.tvSubmit.setOnClickListener(this);
        binding.ivDel.setOnClickListener(this);

        viewModel.getCompanyTypes();
        viewModel.getMemberLevels();

        //申请人填写监听
        binding.tvComName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (popupCan){
                    String s = binding.tvComName.getText().toString();
                    viewModel.search(s);
                }

                if (TextUtils.isEmpty(charSequence)){
                    binding.tvBossName.setText("");
                    binding.tvAddress.setText("");
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    public void showCompanyList(List<CompanyEntity> list){
        companyEntities.clear();
        companyEntities.addAll(list);
        if (showPopup){
            if (popupwindowAdapter != null){
                popupwindowAdapter.notifyDataSetChanged();
            }
        }else {
            showPopupwindow();
        }
    }

    public void setCompanyTypes(List<UnitEntity> list){
        comTypes.clear();
        comTypes.addAll(list);
    }

    public void setMemberLevels(List<UnitEntity> list){
        memLevels.clear();
        memLevels.addAll(list);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_comType:
                showComTypePop();
                break;
            case R.id.ll_memLevel:
                showMemLevelPop();
                break;
            case R.id.iv_del:
                binding.tvComName.setText("");
                binding.tvBossName.setText("");
                binding.tvAddress.setText("");
                popupCan = true;
                break;
            case R.id.tv_submit:
                if (TextUtils.isEmpty(binding.tvComName.getText())){
                    MToast.showToast(AddMemberActivity.this, "请输入企业名称");
                    return;
                }
                if (TextUtils.isEmpty(binding.etContact.getText())){
                    MToast.showToast(AddMemberActivity.this, "请输入联系人名称");
                    return;
                }
                if (TextUtils.isEmpty(binding.etContactNumber.getText())){
                    MToast.showToast(AddMemberActivity.this, "请输入联系电话");
                    return;
                }
                if (TextUtils.isEmpty(binding.tvComType.getText())){
                    MToast.showToast(AddMemberActivity.this, "请选择企业服务类型");
                    return;
                }
                if (TextUtils.isEmpty(binding.tvMemLevel.getText())){
                    MToast.showToast(AddMemberActivity.this, "请选择会员等级");
                    return;
                }

                createMemberEntity.setConcat(binding.etContact.getText().toString());
                createMemberEntity.setConcatNum(binding.etContactNumber.getText().toString());

                createMemberEntity.setEmployeeNum(binding.etMemNumber.getText().toString());
                createMemberEntity.setTurnover(binding.etMoney.getText().toString());
                createMemberEntity.setBankLevel(binding.etBankLevel.getText().toString());
                createMemberEntity.setBankLoan(binding.etLoan.getText().toString());
                createMemberEntity.setAssets(binding.etFixedAssets.getText().toString());
                createMemberEntity.setProduct(binding.etBySelfMake.getText().toString());
                //调接口
                viewModel.submit(createMemberEntity);
                break;
        }

    }

    /**
     * 选择企业弹框
     */
    public void showPopupwindow(){
        binding.grayLayout.setVisibility(View.VISIBLE);
        View popupView = getLayoutInflater().inflate(R.layout.car_popwindows, null);
        XRecyclerView recyclerView = popupView.findViewById(R.id.lsvMore);
        popupwindowAdapter = new CompanyPopupwindowAdapter(AddMemberActivity.this, companyEntities);
        leftManager = new GridLayoutManager(this, 1);
        recyclerView.setLayoutManager(leftManager);
        recyclerView.setAdapter(popupwindowAdapter);
        recyclerView.setPullRefreshEnabled(false);
        recyclerView.setLoadingMoreEnabled(false);
        WindowManager wm = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        window = new PopupWindow(popupView, width, height/3);
        window.setAnimationStyle(R.style.popwindow_dropdown);
        window.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F8F8F8")));
        window.setFocusable(false);
        window.setOutsideTouchable(false);
        window.update();
        window.showAsDropDown(binding.tvBossName, 0, 0);
        showPopup = true;

        popupwindowAdapter.setOnItemClickLitener(new CompanyPopupwindowAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                popupCan=false;
                binding.tvComName.setText(companyEntities.get(position).getName());
                binding.tvAddress.setText(companyEntities.get(position).getAddress());
                binding.etContact.setText(companyEntities.get(position).getConcat());
                binding.etContactNumber.setText(companyEntities.get(position).getPhone());
                binding.tvBossName.setText(companyEntities.get(position).getLegalPerson());

                createMemberEntity.setCompanyName(companyEntities.get(position).getName());
                createMemberEntity.setCompanyNo(companyEntities.get(position).getNo());

                binding.grayLayout.setVisibility(View.GONE);
                showPopup = false;
                hideKeyboard();
                window.dismiss();
            }
        });
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     */
    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        // 隐藏软键盘
        imm.hideSoftInputFromWindow(this.getWindow().getDecorView().getWindowToken(), 0);
    }

    //企业服务类型选择器
    private void showComTypePop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(AddMemberActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String content = comTypes.get(options1).getName();
                createMemberEntity.setCompanyType(comTypes.get(options1).getName());
                binding.tvComType.setText(content);
                comTypePosition = options1;
            }
        }).setDecorView(getWindow().getDecorView().findViewById(android.R.id.content)).build();
        businessOption.setPicker(comTypes);
        businessOption.setSelectOptions(comTypePosition);
        businessOption.show();
    }

    //会员等级选择器
    private void showMemLevelPop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(AddMemberActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String content = memLevels.get(options1).getName();
                createMemberEntity.setMemberLevelId(Integer.parseInt(memLevels.get(options1).getId()));
                binding.tvMemLevel.setText(content);
                memLevelPosition = options1;
            }
        }).setDecorView(getWindow().getDecorView().findViewById(android.R.id.content)).build();
        businessOption.setPicker(memLevels);
        businessOption.setSelectOptions(memLevelPosition);
        businessOption.show();
    }

    public void showApprovalFlow(ApprovalFlowEntity data) {
        binding.listFlow.setVisibility(View.VISIBLE);
        binding.tvBlank.setVisibility(View.GONE);

        ApprovalDepartAdapter adapter = new ApprovalDepartAdapter(this, data.getApprover());
        binding.listFlow.setAdapter(adapter);
        binding.listFlow.setLayoutManager(new LinearLayoutManager(this));
    }

    public void setBlank(){
        binding.tvBlank.setVisibility(View.VISIBLE);
    }
}
